<!--
 * @Description: 
 * @Author: yyang
 * @Date: 2023-02-09 09:24:36
 * @LastEditTime: 2023-06-02 16:40:01
 * @LastEditors: yyang
 * @Reference: 
-->
<script setup lang="ts">
import { ref, reactive, watchEffect, toRefs } from "vue";
import { Field, Popup, DatePicker, type FieldRule } from "vant";
import { computed } from "vue";

interface DateArr {
	data: string[];
}

interface SelectInfo {
	label?: string; // 名称项
	modelValue?: string; // 双向绑定
	name?: string; // key值
	placeholder?: string; // 提示文字
	required?: boolean; // 是否必填，默认否
	allowClear?: boolean; // 是否需要删除按钮，默认否
	rules?: FieldRule[]; // 验证规则
}

const propsData = withDefaults(defineProps<SelectInfo>(), {
	placeholder: "请输入",
});

const emits = defineEmits<{
	(e: "update:modelValue", val: string): void;
}>();

const showPicker = ref(false);
const rightIcon = ref("");
const isLink = ref(true);

const dateArr: DateArr = reactive({ data: [] });
const { data } = toRefs(dateArr);

// 文本展示值
const result = computed({
	get: () => propsData.modelValue,
	set: val => {
		emits("update:modelValue", val ?? "");
	},
});

// 确认选择
const onConfirm = function (selectedDate: any) {
	showPicker.value = false;
	const { selectedValues } = selectedDate;
	const dateVal = selectedValues.join("-");
	result.value = dateVal;
	rightIcon.value = "clear";
};

// 点击事件
const inputClick = function (e: any) {
	if (e.target.className.indexOf("van-icon-clear") !== -1) {
		dateArr.data = [];
		result.value = "";
	} else {
		showPicker.value = true;
	}
};

// 监听值改变
watchEffect(() => {
	console.log(1);
	if (propsData.modelValue) {
		rightIcon.value = "clear";
		isLink.value = false;
		data.value = propsData.modelValue.split("-");
	} else {
		rightIcon.value = "";
		isLink.value = true;
		data.value = [];
	}
});
</script>
<template>
	<field
		v-model="result"
		readonly
		:placeholder="propsData.placeholder"
		:right-icon="rightIcon"
		:is-link="isLink"
		:name="propsData.name"
		:required="propsData.required"
		:label="propsData.label"
		:rules="propsData.rules"
		@click="inputClick" />
	<popup v-model:show="showPicker" round position="bottom">
		<date-picker v-model="data" @cancel="showPicker = false" @confirm="onConfirm" />
	</popup>
</template>
